<?php

require_once 'cssmin.php';

/*
 *
 * Copyright (c) 2009 Cam Spiers
 * Licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) license
 *
 */

/**
 *
 * cssmin-combine
 *
 * @name     cssmin-combine
 * @version  0.1
 * @author   Cam Spiers (camspiers [at] gmail [dot] com)
 * @requires cssmin http://code.google.com/p/cssmin/
 *
 * Simple combine function for use in conjunction with cssmin

/**
 * Example usage:
 * 
	echo cssmin_combine('combined.css', array(
		'example1.css',
		'example2.css'
	), isset($_GET['flush']));
 * 
 */

function cssmin_combine($outputFile, $files, $flush = false)
{

	if (file_exists($outputFile) && !$flush) {

		$combinedFileTime = filemtime($outputFile);

		$srcLastMod = 0;

		foreach ($files as $file) {

			$srcLastMod = max(filemtime( $file ), $srcLastMod);

		}

		$refresh = $srcLastMod > $combinedFileTime;

	} else {

		$refresh = true;

	}

	if ($refresh) {

		$combinedData = '';

		foreach ($files as $file) {

			$fileContent = file_get_contents($file);

			if (stripos($file, 'min.css') === false) {

				set_time_limit(0);

				$fileContent = cssmin::minify($fileContent);

			}

			$combinedData .= "/****** FILE: $file *****/\n" . $fileContent . "\n\n";

		}

		file_put_contents($outputFile, $combinedData);

		$combinedFileTime = filemtime($outputFile);

	}
	
	return '<link rel="stylesheet" href="' . $outputFile . '?t=' . $combinedFileTime . '" type="text/css">';

}
